<?php

namespace app\admin\validate;

use think\Db;
use think\Validate;

/**
 * goods验证器
 */
class Rbac extends Validate
{

    protected $rule = [
        'name' => 'require|max:15',
        'remark' => 'require|max:50',
        'status' => 'in:0,1',
        'role_id' => 'require|exists:role',
        'rule_route' => 'require|checkRoute', //角色添加路由时用
        'user_id' => 'require|exists:user',
        'route' => 'require|max:255', //添加规则时用
        'rule_id' => 'require|exists:rule,rule_id',
    ];
    protected $message = [
        'name.max' => '名字不宜过长，15个汉字内适宜',
        'remark.max' => '描述不宜过长，50个汉字内适宜',
        'role_id.require' => 'role_id字段必须存在',
        'role_id.exists' => 'role_id不存在',
    ];
    protected $scene = [
        'addRole' => ['name', 'remark'],
        'editRole' => ['name', 'remark', 'role_id', 'status'],
        'deleteRole' => ['role_id'],

        'editRoleRule' => ['rule_id'=>'require', 'role_id'],
        'editRoleUser' => ['user_id'=>'require', 'role_id'],
        'getRoleRule' => ['role_id'],

        'addUserRole' => ['role_id', 'user_id'],
        'deleteUserRole' => ['role_id', 'user_id'],
        'deleteUserRule' => ['role_id', 'user_id'],
        'getUserRule' => ['role_id'],

        'addRule' => ['name', 'route'],
        'deleteRule' => ['rule_id'],
        'editRule' => ['rule_id', 'name', 'status', 'route'],

        'getUserRole' => ['user_id'],

        'editUserRole' => ['role_id'=>'require', 'user_id'],
    ];
    // 自定义exists规则，exists:table,字段,排除的某个值  即若验证的值与排除的值相等则返回true
    protected function exists($value, $rule, $data, $field)
    {
        if (is_string($rule)) {
            $rule = explode(',', $rule);
        }
        if (isset($rule[2]) && $value == $rule[2]) {
            return true;
        }
        $db = Db::name($rule[0]);
        $key = isset($rule[1]) ? $rule[1] : $field;
        if (strpos($key, '^')) {
            // 支持多个字段验证
            $fields = explode('^', $key);
            foreach ($fields as $key) {
                $map[$key] = $data[$key];
            }
        } elseif (strpos($key, '=')) {
            parse_str($key, $map);
        } else {
            $map[$key] = $data[$field];
        }
        if ($db->where($map)->find()) {
            return true;
        }
        return false;
    }
}
